<template>
  <div class="wrap">
    <div class="header">
      <h3 class="title">至简医考</h3>
      <div class="login">
        <el-form ref="loginForm" :inline="true" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
          <el-form-item prop="username" label="用户名">
            <el-input v-model="loginForm.username" name="username" type="text" auto-complete="on" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input
              :type="pwdType"
              v-model="loginForm.password"
              name="password"
              auto-complete="on"
              placeholder="请输入密码"
              @keyup.enter.native="handleLogin" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <banner />
    <news />
    <links />
  </div>
</template>

<script>
import banner from './banner/index.vue'
import news from './news/index.vue'
import links from './link/index.vue'
import axios from 'axios'
import { setToken } from '@/utils/auth'
import { USERINFO, EXERCISE_TYPE } from '@/constants/storage'
export default {
  components: {
    banner,
    news,
    links
  },
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      loading: false,
      pwdType: 'password'
    }
  },
  methods: {
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          axios.post('/user', this.loginForm).then(res => {
            this.loading = false
            if (res.success) {
              setToken(res.token)
              sessionStorage.setItem(USERINFO, JSON.stringify(res.userInfo))
              sessionStorage.setItem(EXERCISE_TYPE, res.examType)
              this.$router.push({ path: '/exercise' })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .header {
    position: relative;
    width: 1200px;
    left: 50%;
    margin-left: -600px;
    z-index: 999;
    height: 84px;
    line-height: 34px;
    color: #eee;
    padding-top: 11px;
  }
  .title {
    margin: 0;
    float: left;
    vertical-align: middle;
    color: #007aff;
  }

  .login {
    float: right;
    margin-right: 100px;
    vertical-align: middle;
    color: #007aff;
    transition: .6s;
    &:hover {
      color: #E6A23C;
    }
  }

</style>
